package com.amor.workpcs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amor.workpcs.entity.*;
import com.amor.workpcs.dao.CompanyDao;
import com.amor.workpcs.service.*;
import com.amor.workpcs.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Company)表服务实现类
 *
 * @author makejava
 * @since 2021-09-14 10:25:19
 */
@Service("companyService")
public class CompanyServiceImpl implements CompanyService {
    @Resource
    private CompanyDao companyDao;
    @Autowired
    StaffService staffService;
    @Autowired
    WorkOrderService workOrderService;
    @Autowired
    PersonalService personalService;
    @Autowired
    GroupService groupService;

    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");


    /**
     * 通过ID查询单条数据
     *
     * @param companyId 主键
     * @return 实例对象
     */
    @Override
    public Company queryById(Integer companyId) {
        return this.companyDao.queryById(companyId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Company> queryAllByLimit(int offset, int limit) {
        return this.companyDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param company 实例对象
     * @return 实例对象
     */
    @Override
    public Company insert(Company company) {
        this.companyDao.insert(company);
        return company;
    }

    /**
     * 修改数据
     *
     * @param company 实例对象
     * @return 实例对象
     */
    @Override
    public Company update(Company company) {
        this.companyDao.update(company);
        return this.queryById(company.getCompanyId());
    }

    /**
     * 通过主键删除数据
     *
     * @param companyId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer companyId) {
        return this.companyDao.deleteById(companyId) > 0;
    }

    @Override
    @Transactional
    public void initInsert() {
        //获取所有人员信息
        Map<String, Object> personalMap = new HashMap<>();
        personalMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");
        JSONObject personalJson = HttpUtil.post("https://open.ashcloudsolution.com/openApi/v1/personnel/staff/get_staff_list", personalMap);
        personalJson = (JSONObject) personalJson.get("result");
        JSONArray jsonArray = (JSONArray) personalJson.get("data");
        //获取每一个JsonArray数据
        JSONObject dataTemp;
        Staff staff = new Staff();
        List<Staff> staffList = staffService.list();

        //员工详情
//        Map<String,Object> personalDetailMap = new HashMap<>();
//        personalDetailMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");

        //循环平台返回数据
        for (int i = 0; i < jsonArray.size(); i++) {
            dataTemp = (JSONObject) jsonArray.get(i);
            if (staffList.size() == 0) {
                //初始化导入数据
                staff.setName(dataTemp.getString("staff_name"));
                staff.setGender(dataTemp.getString("sex"));
                staff.setGroupName(dataTemp.getString("group_name"));
//                    staff.setComein(dataTemp.getDate("comein"));
                staff.setDepartment(dataTemp.getString("branch_name"));
                staff.setWorkStatus(dataTemp.getString("estate"));
                staff.setJob(dataTemp.getString("job_name"));
                staff.setWorkAddress(dataTemp.getString("workadd_name"));
                staff.setPhoto(dataTemp.getString("photo_path"));
                staff.setStaffId(Integer.parseInt(dataTemp.getString("staff_id")));
                staffService.insert(staff);
            } else {
                //循环本地人员数据
                for (int j = 0; j < staffList.size(); j++) {
//                    System.out.println(staffList.get(j).getStaffId());

                    //如果有新员工，则新增
                    if (!dataTemp.get("staff_id").equals(staffList.get(j).getStaffId())) {
                        staff.setName(dataTemp.getString("staff_name"));
                        staff.setGender(dataTemp.getString("sex"));
                        staff.setGroupName(dataTemp.getString("group_name"));
//                    staff.setComein(dataTemp.getDate("comein"));
                        staff.setDepartment(dataTemp.getString("branch_name"));
                        staff.setWorkStatus(dataTemp.getString("estate"));
                        staff.setJob(dataTemp.getString("job_name"));
                        staff.setWorkAddress(dataTemp.getString("workadd_name"));
                        staff.setPhoto(dataTemp.getString("photo_path"));
                        staff.setStaffId(Integer.parseInt(dataTemp.getString("staff_id")));
                        staffService.insert(staff);
                    }
                    //更新小组
//                    personalDetailMap.put("staff_id",staffList.get(j).getStaffId());
//                    JSONObject personalDetailJson = HttpUtil.post("https://open.ashcloudsolution.com/openApi/v1/personnel/staff/get_staff_info",personalDetailMap);
//                    if(!staffList.get(j).getGroupName().equals(personalDetailJson.getString("group"))){
//                        staff.setGroupName(personalDetailJson.getString("group"));
//                        staffService.update(staff);
//                    }
//                    if(staffList.get(j).getDepartment().equals(personalDetailJson.getString("branch"))){
//
//                    }
                }
            }
        }


        //获取生产部门信息
        Map<String, Object> departmentMap = new HashMap<>();
        departmentMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");
        JSONObject departmentJson = HttpUtil.post("https://open.ashcloudsolution.com/openApi/v1/produce/workshop/get_workshop_list", departmentMap);
        departmentJson = departmentJson.getJSONObject("result");
        JSONArray departmentArray = departmentJson.getJSONArray("data");
        JSONObject departmentTemp;
        //工单详情
        Map<String, Object> DepartmentMap = new HashMap<>();
        DepartmentMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");
//        departmentMap.put("sc_date",simpleDateFormat.format(new Date()));
        departmentMap.put("sc_date", "2021-09-09");
        //生产工单详情
        Map<String, Object> workOrderDetailMap = new HashMap<>();
        workOrderDetailMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");
        //员工详情
        Map<String, Object> personalDetailMap = new HashMap<>();
        //工单详情中转
        JSONObject workOrderDetailTemp;

        //获取小组数量
        int groupSize = staffService.groupSize().size();

        //循环平台返回生产部门列表
        for (int i = 0; i < departmentArray.size(); i++) {

            departmentTemp = (JSONObject) departmentArray.get(i);
            DepartmentMap.put("workshop_id", departmentTemp.get("workshop_id"));
            //获取生产单位生产记录
            JSONObject workOrderDetailJson = HttpUtil.post("https://open.ashcloudsolution.com/openApi/v1/produce/workshop/get_output_list", DepartmentMap);
            workOrderDetailJson = workOrderDetailJson.getJSONObject("result");
            JSONArray workOrderDetailArray = workOrderDetailJson.getJSONArray("data");
            //循环生产单位记录
            for (int j = 0; j < workOrderDetailArray.size(); j++) {
                workOrderDetailTemp = (JSONObject) workOrderDetailArray.get(i);
                workOrderDetailTemp.get("sc_qty");
//                workOrderDetailTemp.get("creator");
                personalDetailMap.put("name", workOrderDetailTemp.get("creator"));
                Staff staff1 = staffService.selectByMap(personalDetailMap);
                System.out.println(staff1.getName());
                //比较output_id看看是否相同，如果不相同就存入数据库，相同不管
                List<WorkOrder> workOrderList = workOrderService.list();
                if (workOrderList.size() == 0 && staff1 != null) {
//                    Map<String,Object> staffNameMap = new HashMap<>();
//                    staffNameMap.put("name",)
//                    staffService.selectByMap();

                    //添加个人初始化数据
                    Personal personal = new Personal();
//                    personal.setPersonalName(((JSONObject) workOrderDetailArray.get(i)).getString("creator"));
                    personal.setPersonalName(staff1.getName());
                    personal.setGroupName(staff1.getGroupName());
                    personal.setDepartmentName(staff1.getDepartment());
//                    Integer.parseInt(String.valueOf(workOrderDetailTemp.getInteger("sc_qty")));
                    personal.setPersonalTodayQuantity(String.valueOf(Integer.parseInt(String.valueOf(workOrderDetailTemp.getInteger("sc_qty"))) / groupSize));
                    personal.setPersonalTodayPrice(workOrderDetailTemp.getDoubleValue("price") * (Integer.parseInt(String.valueOf(workOrderDetailTemp.getInteger("sc_qty"))) / groupSize));
                    personal.setCreator(workOrderDetailTemp.getString("creator"));
                    personal.setCreateDate(workOrderDetailTemp.getDate("created"));

                    //添加小组初始化数据
                    Group group = new Group();
                    Staff staff2 = staffService.selectByMap((Map<String, Object>) new HashMap<>().put("name", workOrderDetailTemp.getString("creator")));
                    group.setGroupName(staff2.getGroupName());
                    group.setGroupTodayQuantity(workOrderDetailTemp.getString("sc_qty"));
                    group.setGroupTodayPrice(workOrderDetailTemp.getDoubleValue("price"));
                    group.setCreator(workOrderDetailTemp.getString("creator"));
                    group.setCreatorDate(workOrderDetailTemp.getDate("created"));

                    //添加部门初始化数据
                    Department department = new Department();
                    department.setDepartmentName(staff2.getDepartment());


                } else {
                    //添加新数据


                }


            }

        }


    }

    @Override
    @Transactional
    public void init() {
        Map<String, Object> personalMap = new HashMap<>();
        personalMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");
        JSONObject personalJson = HttpUtil.post("https://open.ashcloudsolution.com/openApi/v1/personnel/staff/get_staff_list", personalMap);
        JSONArray jsonArray = personalJson.getJSONObject("result").getJSONArray("data");
        Staff staff = new Staff();
        for (int i = 0; i < jsonArray.size(); i++) {
            staff.setName(jsonArray.getJSONObject(i).getString("staff_name"));
            staff.setGender(jsonArray.getJSONObject(i).getString("sex"));
            staff.setGroupName(jsonArray.getJSONObject(i).getString("group_name"));
            staff.setDepartment(jsonArray.getJSONObject(i).getString("branch_name"));
            staff.setWorkStatus(jsonArray.getJSONObject(i).getString("estate"));
            staff.setJob(jsonArray.getJSONObject(i).getString("job_name"));
            staff.setWorkAddress(jsonArray.getJSONObject(i).getString("workadd_name"));
            staff.setPhoto(jsonArray.getJSONObject(i).getString("photo_path"));
            staff.setStaffId(Integer.parseInt(jsonArray.getJSONObject(i).getString("staff_id")));
            staffService.insert(staff);
        }
        //获取生产部门信息
        Map<String, Object> departmentMap = new HashMap<>();
        departmentMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");
        JSONObject departmentJson = HttpUtil.post("https://open.ashcloudsolution.com/openApi/v1/produce/workshop/get_workshop_list", departmentMap);
        JSONArray depaertmentJsonArray = departmentJson.getJSONObject("result").getJSONArray("data");
        //参数
        Map<String, Object> workOrderMap = new HashMap<>();
        workOrderMap.put("secret_key", "YzdmYjVkZmUxYTUzNzYwNmQwMTRlNDY2ZmQzY2NlN2U=");
//        workOrderMap.put("sc_date",simpleDateFormat.format(new Date()));
        workOrderMap.put("sc_date", "2021-09-09");

        //员工详情
        Map<String, Object> personalDetailMap = new HashMap<>();

        //获取小组数量
        int groupSize = staffService.groupSize().size();

        //循环部门
        for (int i = 0; i < depaertmentJsonArray.size(); i++) {
            workOrderMap.put("workshop_id", depaertmentJsonArray.getJSONObject(i).getString("workshop_id"));
            JSONObject workOrderDetailJson = HttpUtil.post("https://open.ashcloudsolution.com/openApi/v1/produce/workshop/get_output_list", workOrderMap);
            JSONArray workOrderDetailArray = workOrderDetailJson.getJSONObject("result").getJSONArray("data");
            //循环生产工单详情记录
            for (int j = 0; j < workOrderDetailArray.size(); j++) {
//                for (int x = 0; x < jsonArray.size(); x++) {
//                    if (workOrderJsonObject.equals(jsonArray.getJSONObject(x).getString("staff_name"))){
//
//                    }
//                }

                personalDetailMap.put("name", workOrderDetailArray.getJSONObject(i).getString("creator"));

                //这里不知道行不行
                Staff staff1 = staffService.selectByMap(personalDetailMap);
                //添加个人初始化数据
                Personal personal = new Personal();
                personal.setPersonalName(staff1.getName());
                personal.setGroupName(staff1.getGroupName());
                personal.setDepartmentName(staff1.getDepartment());
                personal.setPersonalTodayQuantity(String.valueOf(workOrderDetailArray.getJSONObject(j).getInteger("sc_qty") / groupSize));
                personal.setPersonalTodayPrice((workOrderDetailArray.getJSONObject(j).getDouble("price") * workOrderDetailArray.getJSONObject(j).getDouble("sc_qty") / groupSize));
                personal.setCreator(workOrderDetailArray.getJSONObject(j).getString("creator"));
                personal.setCreateDate(workOrderDetailArray.getJSONObject(j).getDate("created"));
                personalService.insert(personal);

                //添加小组初始化数据
                Group group = new Group();
                group.setGroupName(staff1.getGroupName());
//                group.setDepartmentId(staff1.getDepartment());
                group.setGroupTodayQuantity(workOrderDetailArray.getJSONObject(j).getString("sc_qty"));
                group.setGroupTodayPrice(workOrderDetailArray.getJSONObject(j).getDoubleValue("price"));
                group.setCreator(workOrderDetailArray.getJSONObject(j).getString("creator"));
                group.setCreatorDate(workOrderDetailArray.getJSONObject(j).getDate("created"));
                groupService.insert(group);


                //添加部门初始化数据
                Department department = new Department();
                department.setDepartmentName(staff1.getDepartment());
                department.setCreator(staff1.getName());
                department.setCreateDate(workOrderDetailArray.getJSONObject(j).getDate("created"));


            }
        }
    }


    /**
     *
     * @Author: Amor
     * @Date: 10:32 2021/10/8
     * @Description: 初始化插入数据
     */


}